package com.wf.smartcomm.server.weixin.action;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Random;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import com.cloopen.rest.sdk.CCPRestSDK;
import com.cloopen.rest.sdk.CCPRestSmsSDK;
import com.opensymphony.xwork2.ModelDriven;
import com.wf.smartcomm.server.bean.User;
import com.wf.smartcomm.server.client.action.BaseAction;
import com.wf.smartcomm.server.response.ResponseCode;
import com.wf.smartcomm.server.service.UserService;
import com.wf.smartcomm.server.util.ConstantUtils;
import com.wf.smartcomm.server.util.IdUtils;
import com.wf.smartcomm.server.util.PushUtils;
import com.wf.smartcomm.server.util.StringUtil;

@Service
@Scope("prototype")
public class LoginAction extends BaseAction implements ModelDriven<User>{

	private User user = new User();
	
	@Resource
	private UserService userServiceImpl;

	public void getSms() throws IOException{
		HashMap<String, Object> result = null;
		String[] random = {"0","1","2","3","4","5","6","7","8","9"};
		String validationCode = "";
		for (int i = 0; i < 4; i++) {
			Random index = new Random();
			validationCode+=random[index.nextInt(10)];
		}
		//初始化SDK
		CCPRestSmsSDK restAPI = new CCPRestSmsSDK();
		if (PushUtils.isDevEnv) {
			restAPI.init("sandboxapp.cloopen.com", "8883");
			restAPI.setAccount("8a48b551516c09cd01516c36b1cf00dd", "a989200a4e29483cb3e5d6107ae9fdd0");
			restAPI.setAppId("aaf98f89516bf50b01516c39b27b0152");
			result = restAPI.sendTemplateSMS(user.getPhoneNumber(),"1" ,new String[]{validationCode,"5"});
		} else {
			restAPI.init("app.cloopen.com", "8883");
			restAPI.setAccount(PushUtils.pushConfig.getProperty("CloudMainAccount"), PushUtils.pushConfig.getProperty("CloudMainToken"));
			restAPI.setAppId(PushUtils.pushConfig.getProperty("CloudAppId"));
			result = restAPI.sendTemplateSMS(user.getPhoneNumber(),"52987" ,new String[]{validationCode,"5"});
		}
		
		System.out.println("SDKTestGetSubAccounts result=" + result);
		if("000000".equals(result.get("statusCode"))){
			//正常返回输出data包体信息（map）
			HashMap<String,Object> data = (HashMap<String, Object>) result.get("data");
			Set<String> keySet = data.keySet();
			for(String key:keySet){
				Object object = data.get(key);
				System.out.println(key +" = "+object);
			}
//			HttpSession session = request.getSession();
//			session.setAttribute("code", validationCode);
			Cookie cookie = new Cookie("validationCode",validationCode+"");
			cookie.setMaxAge(300);
			response.addCookie(cookie);
			printJsonData(200);
		}else{
			//异常返回输出错误码和错误信息
			System.out.println("错误码=" + result.get("statusCode") +" 错误信息= "+result.get("statusMsg"));
			HashMap<String,Object> errorMap = new HashMap<String, Object>();
			errorMap.put("errorMsg", result.get("statusMsg"));
			printJsonData(gson.toJson(errorMap));
		}
	}
	
	public void registe() throws IOException{
		User exist = userServiceImpl.getUserByUsername(user.getUsername());
		if (exist != null) {
			if (StringUtil.isEmpty(exist.getOpenId())) {
				exist.setOpenId(user.getOpenId());
				userServiceImpl.update(exist);
				request.getSession().setAttribute("user", exist);
				Cookie cookie = new Cookie("userId",user.getObjectId());
				cookie.setMaxAge(3600*24*30*12*2);
				response.addCookie(cookie);
			}
			printJsonData(202);
			return;
		}
		if (StringUtil.isEmpty(user.getOpenId())) {
			printJsonData(201);
			return;
		}
		user.setUserType(ConstantUtils.USER_TYPE_WEIXIN);
		user.setType(ConstantUtils.USER_TYPE_UNKNOW);
		user.setId(IdUtils.MD5(user.getId()));
		user.setPassword(IdUtils.MD5("123456"));
		userServiceImpl.registe(user);
		request.getSession().setAttribute("user", user);
		Cookie cookie = new Cookie("userId",user.getObjectId());
		cookie.setMaxAge(3600*24*30*12*2);
		response.addCookie(cookie);
		HashMap<String, Object> result = null;
		CCPRestSDK restAPI = new CCPRestSDK();
		if (PushUtils.isDevEnv) {
			restAPI.init("sandboxapp.cloopen.com", "8883");
			restAPI.setAccount("8a48b551516c09cd01516c36b1cf00dd", "a989200a4e29483cb3e5d6107ae9fdd0");
			restAPI.setAppId("aaf98f89516bf50b015180a2d42a2875");
		} else {
			restAPI.init(PushUtils.pushConfig.getProperty("CloudAddress"), PushUtils.pushConfig.getProperty("CloudPort"));// 初始化服务器地址和端口，格式如下，服务器地址不需要写https://
			restAPI.setAccount(PushUtils.pushConfig.getProperty("CloudMainAccount"), PushUtils.pushConfig.getProperty("CloudMainToken"));// 初始化主帐号和主帐号TOKEN
			restAPI.setAppId(PushUtils.pushConfig.getProperty("CloudAppId"));// 初始化应用ID
		}
		result = restAPI.createSubAccount(user.getObjectId());
		System.out.println("SDKTestCreateSubAccount result=" + result);
		if("000000".equals(result.get("statusCode"))){
			//正常返回输出data包体信息（map）
			HashMap<String,Object> data = (HashMap<String, Object>) result.get("data");
			List<HashMap<String,Object>> object =  (List<HashMap<String,Object>>) data.get("SubAccount");
			for (HashMap<String, Object> hashMap : object) {
				if (hashMap.containsKey("subAccountSid")) {
					user.setSubAccountSid(hashMap.get("subAccountSid").toString());
				}
				if (hashMap.containsKey("voipAccount")) {
					user.setVoipAccount(hashMap.get("voipAccount").toString());
				}
				if (hashMap.containsKey("voipPwd")) {
					user.setVoipPwd(hashMap.get("voipPwd").toString());
				}
				if (hashMap.containsKey("subToken")) {
					user.setSubToken(hashMap.get("subToken").toString());
				}
			}
			userServiceImpl.initVoipInfo(user);
			
		}else{
			//异常返回输出错误码和错误信息
			System.out.println("错误码=" + result.get("statusCode") +" 错误信息= "+result.get("statusMsg"));
		}
		
		printJsonData(200);
	}
	
	public void login() throws Exception{
		user.setPassword(IdUtils.MD5(user.getPassword()));
		User exist = userServiceImpl.login(user);
		if (exist != null) {
			exist.setOpenId(user.getOpenId());
			userServiceImpl.update(exist);
			request.getSession().setAttribute("user", exist);
			Cookie cookie = new Cookie("userId",exist.getObjectId());
			cookie.setMaxAge(3600*24*30*12*2);
			response.addCookie(cookie);
			printJsonData(200);
		}else {
			printJsonData(201);
		}
	}

	@Override
	public User getModel() {
		return user;
	}

}
